package de.fhtrier.gdw2.ships.network;

import de.fhtrier.gdw.commons.netcode.NetConnection;
import de.fhtrier.gdw.commons.netcode.datagram.INetDatagram;
import de.fhtrier.gdw2.ships.SpaceshipGame;
import de.fhtrier.gdw2.ships.network.datagrams.ConnectDatagram;
import de.fhtrier.gdw2.ships.network.datagrams.DatagramFactory;
import de.fhtrier.gdw2.ships.network.datagrams.DatagramType;
import de.fhtrier.gdw2.ships.network.datagrams.LevelDatagram;
import de.fhtrier.gdw2.ships.states.GameplayState;

/**
 *
 * @author Lusito
 */
public class NetGameClient extends NetGame {

	private NetConnection serverConnection;

	public NetGameClient(String ip, int port, String playerName) {
		try {
			serverConnection = new NetConnection(ip, port, new DatagramFactory());
			serverConnection.send(new ConnectDatagram(playerName));
			serverConnection.setAccepted(true);
		} catch (Exception e) {
			serverConnection = null;
			e.printStackTrace();
		}
	}

	@Override
	public boolean isClient() {
		return serverConnection != null && serverConnection.isConnected();
	}

	@Override
	public boolean isServer() {
		return false;
	}

	@Override
	public void shutdown() {
		if (serverConnection != null) {
			serverConnection.shutdown();
			serverConnection = null;
		}
		SpaceshipGame.changeState(SpaceshipGame.GAMESTATE);
	}

	@Override
	public void handleIncoming() {
		if(serverConnection != null && !serverConnection.isConnected())
			shutdown();
		
		if (isClient()) {
			while (serverConnection.hasIncoming()) {
				INetDatagram datagram = serverConnection.receive();
				if (datagram != null)
					handleDatagram(serverConnection, datagram);
			}
		}
	}

	@Override
	public void handleOutgoing() {
		if (isClient()) {
			serverConnection.sendPendingDatagrams();
		}
	}

	public void handleDatagram(NetConnection connection, INetDatagram datagram) {
		GameplayState state = (GameplayState)SpaceshipGame.instance.getState(SpaceshipGame.GAMESTATE);
		switch (datagram.getType()) {
			case DatagramType.CONNECT:
				handleConnect(connection, (ConnectDatagram) datagram);
				break;
            case DatagramType.LEVEL:
                
                state.receiveLevelDatagram((LevelDatagram)datagram);
                break;
            case DatagramType.GAMEOVER:
            	break;
		}
	}

	private void handleConnect(NetConnection connection, ConnectDatagram datagram) {
        SpaceshipGame.changeState(SpaceshipGame.GAMESTATE);
	}
    
	@Override
	public void send(INetDatagram datagram) {
		if (isClient())
			serverConnection.send(datagram);
	}

	@Override
	public void sendEvent(byte type, short id, short param1, short param2) {
		if (isClient())
			serverConnection.sendEvent(type, id, param1, param2);
	}
}
